package edu.cmu.ece.ds.droidchat.util;

import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.facebook.android.Facebook;

import edu.cmu.ece.ds.droidchat.LogInActivity;
import edu.cmu.ece.ds.droidchat.model.StringConstants;
import edu.cmu.ece.ds.droidchat.model.UserInfo;

public class FacebookJsonParser extends AsyncTask<Void, Integer, UserInfo> {
    private static final String TAG = "FacebookJsonParser";
    private LogInActivity activity;
    private Facebook facebook;

    public FacebookJsonParser(LogInActivity activity, Facebook facebook) {
        // urlStr += id;
        this.activity = activity;
        this.facebook = facebook;
    }

    @Override
    public UserInfo doInBackground(Void... voids) {
        UserInfo userInfo = new UserInfo("", "");
        try {
            String fbMyInfoString = facebook
                    .request(StringConstants.FACEBOOK_REQUEST_ME);
            Log.e(TAG, "fbMyInfoString=" + fbMyInfoString);
            JSONObject jsonObj = new JSONObject(fbMyInfoString);
            String id = jsonObj.getString("id");
            String nickname = jsonObj.getString("name");
            String email = jsonObj.getString("email");
            Log.e(TAG, "id=" + id);
            Log.e(TAG, "nickname=" + nickname);
            Log.e(TAG, "email=" + email);
            userInfo.setUsername(email);
            userInfo.setNickName(nickname);
            userInfo.setProfilePicture(Toolbox.loadFacebookProfilePicture(id));
        } catch (Exception e) {
            Log.e(TAG, "Exception getting JSON data", e);
        }
        return userInfo;
    }

    @Override
    public void onPostExecute(UserInfo userInfo) {
        activity.getRegistrationInfoFromFacebook(userInfo);
    }

}
